import TabHeader from '@/components/TabHeader';
import TextButton from '@/components/TextButton';
import { getMergeGamesScores } from '@/funcs/game';
import { AppContext } from '@/store/index.context';
import { Game } from '@/types/game';
import { xor } from 'lodash';
import React, { useContext, useMemo, useState } from 'react';
import HistoryGame from './HistoryGame';
import classes from './index.module.css';
import MergeScores from './MergeScores';

export default function History() {
  const { historyGamesStore } = useContext(AppContext);
  const [showMergeChoice, setShowMergeChoice] = useState(false);

  const { getAllHistoryGames } = historyGamesStore;

  const [mergeGames, setMergeGames] = useState<Game[]>([]);

  const [showMergeScores, setShowMergeScores] = useState(false);

  const [mergeResult, setMergeResult] = useState<{ [key: string]: number }>({});

  const historyGames = useMemo(
    () => getAllHistoryGames(),
    [getAllHistoryGames],
  );

  function handleStartMerge() {
    setShowMergeChoice(!showMergeChoice);
    if (!showMergeChoice) {
      setMergeGames([]);
    }
  }

  function toggleMergeGame(game: Game) {
    setMergeGames(xor(mergeGames, [game]));
  }

  function handleMergeScore() {
    if (mergeGames.length === 0) {
      alert('请选择要合计算分的比赛');
    } else {
      const mergeResult = getMergeGamesScores(mergeGames);
      setShowMergeScores(true);
      setMergeResult(mergeResult);
      console.log(mergeResult);
    }
  }

  return (
    <>
      <TabHeader title="历史对局" />
      <div className={classes.Operations}>
        <TextButton onClick={handleStartMerge}>
          {showMergeChoice ? '取消合计' : '合计算分'}
        </TextButton>
        {showMergeChoice && (
          <TextButton onClick={handleMergeScore}>算分</TextButton>
        )}
      </div>
      <div className={classes.historyGames}>
        {historyGames.map(game => (
          <HistoryGame
            game={game}
            key={game.startTime}
            showMergeChoice={showMergeChoice}
            merged={mergeGames.includes(game)}
            handleSelect={() => toggleMergeGame(game)}
          />
        ))}
      </div>
      {showMergeScores && (
        <MergeScores
          mergeResult={mergeResult}
          handleClose={() => setShowMergeScores(false)}
        />
      )}
    </>
  );
}
